package com.disk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.disk.config.AppConfig;
import com.disk.entity.constants.Constants;
import com.disk.entity.enums.FileCategoryEnums;
import com.disk.entity.po.FileInfo;
import com.disk.entity.vo.FolderVO;
import com.disk.entity.vo.ResponseVO;
import com.disk.exception.BusinessException;
import com.disk.mapper.FileInfoMapper;
import com.disk.service.FileInfoService;
import com.disk.utils.CopyTools;
import com.disk.utils.StringTools;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CommonFileController extends ABaseController {

    @Resource
    private AppConfig appConfig;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private FileInfoMapper fileInfoMapper;

    public void getImage(HttpServletResponse response, String imageFolder, String imageName) {
        if (StringTools.isEmpty(imageName) || StringTools.isEmpty(imageFolder) || !StringTools.pathIsOk(imageFolder)) {
            return;
        }
        String imageSuffix = StringTools.getFileSuffix(imageName);
        String filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + imageFolder + "/" + imageName;
        imageSuffix = imageSuffix.replace(".", "");
        String contentType = "image/" + imageSuffix;
        response.setContentType(contentType);
        response.setHeader("Cache-Control", "max-age=2592000");
        readFile(response, filePath);
    }


    public void getFile(HttpServletResponse response, String fileId, String UserId) {
        String filePath = null;
        if (fileId.endsWith(".ts")) {
            String[] tsArray = fileId.split("_");
            String realFileId = tsArray[0];
            FileInfo fileInfo = fileInfoService.getBaseMapper()
                    .selectOne(new LambdaQueryWrapper<FileInfo>()
                            .eq(FileInfo::getFileId, realFileId)
                            .eq(FileInfo::getUserId, UserId));
            if (fileInfo == null) {
                return;
            }
            String fileName = fileInfo.getFilePath();
            fileName = StringTools.getFileNameNoSuffix(fileName) + "/" + fileId;
            filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileName;
        } else {
            FileInfo fileInfo = fileInfoService.getById(fileId);
            if (fileInfo == null) {
                return;
            }
            if (FileCategoryEnums.VIDEO.getCategory().equals(fileInfo.getFileCategory())) {
                String fileNameNoSuffix = StringTools.getFileNameNoSuffix(fileInfo.getFilePath());
                filePath = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileNameNoSuffix + "/" + Constants.M3U8_NAME;
            }
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
        }
        readFile(response, filePath);
    }

    public ResponseVO getFolderInfo(String path, String userId) {
        String[] pathArray = path.split("/");
        List<FileInfo> fileInfoList = new ArrayList<>();
        // 从最后一层开始查找
        searchFileInfoFromEnd(pathArray, userId, fileInfoList);
        // 将找到的文件信息转为 FolderVO 并返回
        return getSuccessResponseVO(CopyTools.copyList(fileInfoList, FolderVO.class));
    }

    // 从最后一层开始递归查找文件信息
    private void searchFileInfoFromEnd(String[] pathArray, String userId, List<FileInfo> fileInfoList) {
        if (pathArray.length == 0) {
            return; // 如果没有路径，直接返回
        }

        // 从最后一层开始处理
        String currentFileId = pathArray[pathArray.length - 1];

        // 查找文件信息
        FileInfo fileInfo = fileInfoMapper.selectOne(new LambdaQueryWrapper<FileInfo>()
                .eq(FileInfo::getUserId, userId)
                .eq(FileInfo::getFileId, currentFileId)
        );

        if (fileInfo != null) {
            // 递归查找父级 PID
            String parentFilePid = fileInfo.getFilePid();
            if (parentFilePid != null && !parentFilePid.isEmpty()) {
                // 创建新的路径数组，去掉已经处理过的部分
                String[] newPathArray = Arrays.copyOf(pathArray, pathArray.length - 1);
                searchFileInfoFromEnd(newPathArray, userId, fileInfoList);
            }

            // 在递归调用之后添加当前文件信息，这样保证了从根到最深层的顺序
            fileInfoList.add(fileInfo);
        }
    }



}
